package me.ingxin.android.router.compiler.util

import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.TypeSpec
import me.ingxin.android.router.annotaions.App
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.util.ElementFilter

/**
 * Created by ingxin on 2022/4/14
 */
class ProcessorUtil(val env: ProcessingEnvironment) {


    fun writeClass(packageName: String, clazz: TypeSpec) {
        val className = clazz.name ?: return
        FileSpec.builder(packageName, className)
            .addType(clazz)
            .build()
            .writeTo(env.filer)
    }

    /**
     * 检测App注解是否使用并且否唯一
     * @return 如果注解唯一且使用正确，返回使用该注解的类的类名，否则返回null
     */
    fun checkApp(processorName: String, roundEnv: RoundEnvironment, logger: Logger): String? {
        //获取所有App注解
        val annotationList =
            roundEnv.getElementsAnnotatedWith(App::class.java) ?: return null
        val appElementList = ElementFilter.typesIn(annotationList)?.toList() ?: return null

        if (appElementList.isEmpty()) {
            return null
        }
        //App中只能有一个@App
        appElementList.forEach {
            logger.info("$processorName : found [@${App::class.java.simpleName}] in [${it.qualifiedName}]")
        }
        appElementList[0].simpleName
        if (appElementList.size > 1) {
            logger.throwException("There are more than two [@${App::class.java.simpleName}]")
        }
        return appElementList[0].qualifiedName.toString()
    }

}